const db = uniCloud.database();

exports.main = async (event, context) => {
  const now = new Date();
  now.setUTCHours(13, 0, 0, 0); // 北京时间 21:00

  try {
    const collection = db.collection("consultant_schedule");
    const result = await collection.get();

    const updates = result.data.map(async (record) => {
      const recordDate = new Date(record.day);

      // 如果是过去的日期，直接删除该记录
      if (recordDate < now) {
        return collection.doc(record._id).remove();
      }

      const updateData = {};

      // 确保 isShow 为 true
      if (!record.isShow) {
        updateData.isShow = true;
      }

      // 清理掉过期时间段（仅今天或未来）
      const currentTime = now.toTimeString().slice(0, 5);
      const filteredSlots = (record.freeSlots || []).filter(slot => {
        const [startTime] = slot.split("-");
        return startTime >= currentTime;
      });

      updateData.freeSlots = filteredSlots;

      // 若 freeSlots 清空，且想删除“没有剩余时间的记录”，可加判断
      if (filteredSlots.length === 0) {
        return collection.doc(record._id).remove();
      }

      // 有更新才执行更新操作
      if (Object.keys(updateData).length > 0) {
        return collection.doc(record._id).update(updateData);
      }
    });

    await Promise.all(updates);

    return { success: true, message: "数据更新完成" };
  } catch (error) {
    console.error("数据库更新失败:", error);
    return { success: false, message: "数据库更新失败" };
  }
};
